package lex.explorer.model;

import java.io.File;
import javax.swing.filechooser.FileView;

import org.lex.catalog.AbstractCatalogModel;
import org.lex.explorer.FileInfo;
import org.lex.explorer.model.FileSystemModel;
import org.lex.io.filesystem.LocalFileView;


public class DefaultFileSystemModel extends AbstractCatalogModel<FileInfo> implements
		FileSystemModel
{
	private static final FileInfo[] EMPTY = new FileInfo[0];
	private FileInfo dir = null;
	private FileInfo[] children = EMPTY;
	private FileView view = null;

	public DefaultFileSystemModel( File dir )
	{
		this.view = new LocalFileView();
		this.dir = FileInfo.get( view, dir );
	}

	public FileInfo getRoot()
	{
		return null;
	}

	public FileView getFileView()
	{
		return view;
	}

	public void setFileView( FileView view )
	{
		if( null != view )
		{
			this.view = view;
			for( int i = 0, n = children.length; i < n; i++ )
				children[i] = FileInfo.get( view, children[i].getFile() );
			this.fireCatalogChanged( this.dir );
		}
	}

	public FileInfo getCatalog()
	{
		return dir;
	}

	public FileInfo[] getChildren()
	{
		return children;
	}

	public void setCatalog( FileInfo dir )
	{
		this.changeDirectory( dir );
	}

	private void changeDirectory( FileInfo dir )
	{
		File directory = dir.getFile();
		if( null == directory || false == directory.exists() || false == directory.isDirectory() )
		{
			this.children = EMPTY;
		}
		else
		{
			File[] list = directory.listFiles();
			if( null == list )
				children = EMPTY;
			else
			{
				this.children = new FileInfo[list.length];
				for( int i = 0, n = list.length; i < n; i++ )
					children[i] = FileInfo.get( view, list[i] );
			}
			// ln( "cd: " + directory );
			// ln( children.length + " children" );
			this.dir = dir;
		}
		this.fireCatalogChanged( dir );
	}

	void ln( Object o )
	{
		System.out.println( o );
	}
}
